import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { Chat, Message, User } from '../types';
import { currentUser } from '../data/mockData';
import { API_CONFIG } from '../config/apiConfig';
import router from '../router';

export const useChatStore = defineStore('chat', () => {
  // 当前聊天类型：0-知识库AI，1-库存管理AI
  const currentChatType = ref(0);

  // 切换聊天类型
  function switchChatType(type: number) {
    currentChatType.value = type;
    // 清空当前列表并重新加载
    chats.value = [];
    fetchChats();
  }

  // 处理会话过期的方法
  function handleSessionExpired() {
    // 清理所有状态
    chats.value = [];
    messages.value = {};
    activeChat.value = null;
    searchQuery.value = '';
    
    // 清理用户数据
    localStorage.removeItem('userInfo');
    document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
    
    // 使用 replace 而不是 push 来防止用户通过浏览器后退返回
    router.replace('/');
  }
  const chats = ref<Chat[]>([]);
  const messages = ref<Record<string, Message[]>>({});
  const activeChat = ref<string | null>(null);
  const searchQuery = ref('');

  // 添加新会话
  function addChat(newChat: Chat) {
    chats.value.unshift(newChat);
    messages.value[newChat.id] = [];
  }
  
  async function fetchChats() {
    try {
      const url = new URL(`${API_CONFIG.BASE_URL}/chat/page`);
      url.searchParams.append('type', currentChatType.value.toString());
      
      const response = await fetch(url.toString(), {
        credentials: 'include'
      });
      const result = await response.json();
      
      if (result.code === '0') {
        chats.value = result.data.dataList.map((item: { id: string; title: string }) => ({
          id: item.id,
          name: item.title,
          participants: [],
          lastMessage: null
        }));
      }
      else if(result.code === '0001') {
        handleSessionExpired();
        return false;
      }
    }
     catch (error) {
      console.error('获取聊天列表失败:', error);
    }
  }
  
  async function fetchMessages(chatId: string) {
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/chat/record/${chatId}`, {
        credentials: 'include',
      });
      const result = await response.json();
      
      console.log('Raw API response for messages:', result);
      
      if (result.code === '0') {
        // 映射消息并按createTime排序
        const mappedMessages = result.data?.map((msg: { content: string; chatRole: string; createTime: string; type?: number; contentSourceList?: Array<{fileId: string; fileName: string}> }, index: number) => {
          try {
            // 确保使用mockData中定义的用户ID
            const senderId = msg.chatRole === "USER" ? currentUser.id : 'assistant';
            
            // 解析时间，添加错误处理
            let timestamp: Date;
            try {
              timestamp = new Date(msg.createTime);
              if (isNaN(timestamp.getTime())) {
                console.error('Invalid date format:', msg.createTime);
                timestamp = new Date(); // 使用当前时间作为回退
              }
            } catch (error) {
              console.error('Date parsing error:', error);
              timestamp = new Date(); // 使用当前时间作为回退
            }
            
            return {
              id: `msg-${chatId}-${index}-${Date.now()}`, // 生成唯一ID
              content: msg.content,
              senderId,
              timestamp,
              type: msg.type || 1, // 默认为文本消息类型(1)，文件消息为类型(2)
              contentSourceList: msg.contentSourceList // 添加引用文件列表
            };
          } catch (error) {
            console.error('Error mapping message:', error);
            return null;
          }
        }).filter(Boolean) || [];
        
        // 按timestamp升序排列（最早的消息在前）
        mappedMessages.sort((a: Message, b: Message) => {
          return a.timestamp.getTime() - b.timestamp.getTime();
        });
        
        console.log('Mapped and sorted messages:', mappedMessages);
        
        // 确保messages对象已初始化
        if (!messages.value) {
          messages.value = {};
        }
        
        // 使用Vue的响应式API来更新消息
        messages.value = {
          ...messages.value,
          [chatId]: mappedMessages
        };
      } else if(result.code === '0001') {
        handleSessionExpired();
        return false;
      }
    } catch (error) {
      console.error('获取聊天记录失败:', error);
    }
  }

  const filteredChats = computed(() => {
    if (!searchQuery.value) return chats.value;
    return chats.value.filter(chat => 
      chat.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    );
  });

  const currentMessages = computed(() => {
    if (!activeChat.value) return [];
    return messages.value[activeChat.value] || [];
  });

  const getOtherParticipant = (chat: Chat): User => {
    return chat.participants.find(p => p.id !== currentUser.id) || currentUser;
  };

      async function setActiveChat(chatId: string) {
    console.log('Setting active chat:', chatId);
    try {
      activeChat.value = chatId;
      await fetchMessages(chatId);
      console.log('Messages loaded for chat:', chatId);
    } catch (error) {
      console.error('Error loading messages for chat:', chatId, error);
      // 如果加载失败，确保messages数组被初始化为空数组
      messages.value[chatId] = [];
    }
  }

  function addMessage(message: Message) {
    if (!activeChat.value) return;
    
    if (!messages.value[activeChat.value]) {
      messages.value[activeChat.value] = [];
    }
    
    const currentMessages = messages.value[activeChat.value];
    
    // 检查是否存在需要更新的临时消息
    if (!message.id && message.senderId === 'assistant') {
      const lastMessage = currentMessages[currentMessages.length - 1];
      if (lastMessage && lastMessage.senderId === 'assistant' && !lastMessage.id) {
        // 更新现有的临时消息
        lastMessage.content = message.content;
        return;
      }
    }
    
    // 如果是新消息，添加到消息列表
    currentMessages.push(message);
    
    // 更新会话的最后一条消息
    const chatIndex = chats.value.findIndex(c => c.id === activeChat.value);
    if (chatIndex !== -1) {
      // 只有当消息有ID时才更新lastMessage（避免使用临时消息）
      if (message.id) {
        chats.value[chatIndex].lastMessage = message;
      }
    }
  }

  // // 更新现有消息的内容
  // function updateMessage(messageId: string, content: string) {
  //   if (!activeChat.value) return;
    
  //   const currentMessages = messages.value[activeChat.value];
  //   if (!currentMessages) return;
    
  //   const messageIndex = currentMessages.findIndex(msg => msg.id === messageId);
  //   if (messageIndex !== -1) {
  //     currentMessages[messageIndex].content = content;
  //   }
  // }

  async function deleteChat(chatId: string) {
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/chat/${chatId}`, {
        method: 'DELETE',
        credentials: 'include'
      });
      const result = await response.json();
      
      if (result.code === '0') {
        // 从状态中移除会话
        chats.value = chats.value.filter(chat => chat.id !== chatId);
        // 清理会话消息
        delete messages.value[chatId];
        
        // 如果删除的是当前活动会话，重置活动会话
        if (activeChat.value === chatId) {
          activeChat.value = chats.value.length > 0 ? chats.value[0].id : null;
          // 如果还有其他会话，加载新活动会话的消息
          if (activeChat.value) {
            fetchMessages(activeChat.value);
          }
        }
        return true;
      } else if(result.code === '0001') {
        handleSessionExpired();
        return false;
      }
      return false;
    } catch (error) {
      console.error('删除会话失败:', error);
      return false;
    }
  }

  async function updateChatTitle(chatId: string, title: string) {
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/chat/${chatId}?title=${encodeURIComponent(title)}`, {
        method: 'PUT',
        credentials: 'include'
      });
      const result = await response.json();
      
      if (result.code === '0') {
        // 更新本地状态
        const chatIndex = chats.value.findIndex(chat => chat.id === chatId);
        if (chatIndex !== -1) {
          chats.value[chatIndex].name = title;
        }
        return true;
      } else if(result.code === '0001') {
        handleSessionExpired();
        return false;
      }
      return false;
    } catch (error) {
      console.error('重命名会话失败:', error);
      return false;
    }
  }

  function updateSearchQuery(query: string) {
    searchQuery.value = query;
  }

  // 处理文件下载
  async function handleFileDownload(fileId: string, fileName: string) {
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/knowledge-base/file/preview/${fileId}`, {
        credentials: 'include',
      });
      
      if (!response.ok) {
        throw new Error(`下载失败: ${response.status}`);
      }
      
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      
      // 清理
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      
      return true;
    } catch (error) {
      console.error('下载文件失败:', error);
      return false;
    }
  }

  return {
    chats,
    messages,
    activeChat,
    searchQuery,
    currentChatType,
    filteredChats,
    currentMessages,
    getOtherParticipant,
    setActiveChat,
    updateSearchQuery,
    fetchChats,
    fetchMessages,
    addMessage,
    addChat,
    deleteChat,
    updateChatTitle,
    handleSessionExpired,
    switchChatType,
    handleFileDownload
  };
});